package top.ywlog.permission.service;

import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.ywlog.permission.common.RequestHolder;
import top.ywlog.permission.common.request.PageQuery;
import top.ywlog.permission.common.request.UserParam;
import top.ywlog.permission.common.response.PageResult;
import top.ywlog.permission.dao.SysUserMapper;
import top.ywlog.permission.exception.ParamException;
import top.ywlog.permission.model.SysUser;
import top.ywlog.permission.util.IpUtils;
import top.ywlog.permission.util.MD5Utils;
import top.ywlog.permission.util.PasswordUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

/**
 * @author: Durian
 * @date: 2020/10/21 20:29
 * @description:
 */
@Slf4j
@Service
public class SysUserService
{
    @Resource
    private SysUserMapper sysUserMapper;

    /**
     * 用户注册
     *
     * @param userParam param
     * @return password
     */
    @Transactional
    public String addUser(UserParam userParam)
    {
        checkPhoneAndMail(userParam);
        String password = PasswordUtils.randomPassword();
        String encryptPassword = MD5Utils.encrypt(password);
        SysUser user = SysUser.builder().username(userParam.getUsername()).
                telephone(userParam.getTelephone()).mail(userParam.getMail()).
                password(encryptPassword).deptId(userParam.getDeptId()).
                status(userParam.getStatus()).remark(userParam.getRemark()).build();

        user.setOperator(RequestHolder.getCurrentUser().getUsername());
        user.setOperateIp(IpUtils.getRemoteIp(RequestHolder.getCurrentRequest()));
        user.setOperateTime(LocalDateTime.now());

        sysUserMapper.insertSelective(user);
        return password;
    }

    @Transactional
    public void updateUser(UserParam userParam)
    {
        checkPhoneAndMail(userParam);
        SysUser before = sysUserMapper.selectByPrimaryKey(userParam.getId());
        if (before == null)
        {
            log.error("待更新的用户不存在，无法更新 userId:{}", userParam.getId());
            throw new ParamException("待更新的用户不存在，无法更新");
        }

        SysUser after = SysUser.builder().id(userParam.getId()).username(userParam.getUsername()).telephone(userParam.getTelephone()).mail(userParam.getMail())
                .deptId(userParam.getDeptId()).status(userParam.getStatus()).remark(userParam.getRemark()).build();

        after.setOperator(RequestHolder.getCurrentUser().getUsername());
        after.setOperateIp(IpUtils.getRemoteIp(RequestHolder.getCurrentRequest()));
        after.setOperateTime(LocalDateTime.now());

        sysUserMapper.updateByPrimaryKeySelective(after);
    }

    public PageResult<SysUser> page(int deptId, PageQuery pageQuery)
    {
        int count = sysUserMapper.countByDeptId(deptId);
        if (count > 0)
        {
            PageHelper.startPage(pageQuery.getPageNo(), pageQuery.getPageSize());
            List<SysUser> userListByDept = sysUserMapper.getPageByDeptId(deptId);
            return PageResult.<SysUser>builder().total(count).data(userListByDept).build();
        }
        return PageResult.<SysUser>builder().build();
    }

    private boolean checkTelephone(Integer userId, String telephone)
    {
        return sysUserMapper.countByTelephone(telephone, userId) > 0;
    }

    private boolean checkMail(Integer userId, String mail)
    {
        return sysUserMapper.countByMail(mail, userId) > 0;
    }

    private void checkPhoneAndMail(UserParam userParam)
    {
        if (checkTelephone(userParam.getId(), userParam.getTelephone()))
        {
            log.error("用户注册失败，电话{}已被使用", userParam.getTelephone());
            throw new ParamException("该号码已被使用");
        }
        if (checkMail(userParam.getId(), userParam.getMail()))
        {
            log.error("用户注册失败，邮箱{}已被使用", userParam.getMail());
            throw new ParamException("该邮箱已被使用");
        }
    }
}
